// packageF/tourAround/categories/categories.js
const app = getApp();
const skinBehavior = require("../../../utils/themeSkin/skinBehavior");
let location = require("../../../mybehaviors/location/location");
Page({
  behaviors: [skinBehavior,location],
  /**
   * 页面的初始数据
   */
  data: {
    parentId: "",
      query: {
        page: 1,
        longitude: "",
        latitude: "",
        city: "",
        cityCode:'',
        travel_around_goods_type: "",
        is_recommand: "",
        category: "",
        title: "",
        basic_info:1
      },
      active: 0,
      timer: null, //定时器
      secondaryIndex: 0,
      serviceShow: false,
      stairClassify: [],
      secondary: [],
      categoriesGoodsList: [],
       //客服插件
      showKefu: false,
      customer_open: "",
      cservice: "",
      service_mobile: "",
      service_QRcode: '',
      zIndex:100,

      isLoadMore: true,
      totalPage:0,
      total:0,
      siteName:'', //商城名称
      imageUrl:'',
      goodsFlag:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: this.data.themeBaseColor,
    });
    console.log(options,11111);
    if(options.childrenId) {
      this.setData({
        active:Number(options.childrenId),
        'query.city': options.city,
        'query.cityCode': options.cityCode,
        'query.longitude': options.longitude,
        'query.latitude':  options.latitude,
        parentId:options.childrenId
      })
    }
    this.getCategory();
    this.getKefu();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if(!this.data.query.latitude && !this.data.query.longitude) {
      try {
        this._getLocation((mapdata, e) => { //获取定位的城市，拿到定位的信息
          this.setData({
            'query.latitude': e.lat,
            'query.longitude': e.lng,
          });
          this.getGoodsList();
        });
      } catch (e) {
        this.getGoodsList();
      }
    } 
  },
  goodsNavTo(event) {
    let id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageF/tourAround/tourAroundGoodsDetails/tourAroundGoodsDetails?goodsId=' + id,
    })
  },
  secondaryOn(event) {
    let index = event.currentTarget.dataset.index;
    this.setData({
      secondaryIndex: index,
      'query.category': Number(this.data.secondary[index].id),
      'query.page': 1
    });
    this.getGoodsList();
  },
  firstOn(event) {
    let id = event.detail.name;
    this.setData({
      parentId: id,
      'query.page': 1
    })
    // this.getCategoryByParentId();
    this.getCategory();
  },
  searchOn() {
    wx.navigateTo({
      url: `/packageF/tourAround/tourSearch/tourSearch?keyWord=${this.data.query.title}&city=${this.data.query.city}&cityCode=${this.data.query.cityCode}&latitude=${this.data.query.latitude}&longitude=${this.data.query.longitude}`,
    })
  },
  getCategory() {
    let urlStr = app.getNetAddresss("plugin.travel-around.frontend.goods.goods.getCategory");
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          // this.stairClassify = res.data;
        this.setData({
          parentId: this.data.active,
          stairClassify: res.data,
          'query.category': Number(this.data.parentId)
        })
        // this.getCategoryByParentId();
           this.getGoodsList();
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getCategoryByParentId() {
    let data = {
      parent_id: this.data.parentId
    };
    wx.showLoading({
      title: '刷新中...',
    })
    let urlStr = app.getNetAddresss("plugin.travel-around.frontend.goods.goods.getCategoryByParentId");
    app._getNetWork({
      url: urlStr,
      data:data,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          let secondary = res.data;
          this.setData({
            secondary: res.data,
            'query.category': Number(secondary[this.data.secondaryIndex].id)
          })
          
          this.getGoodsList();
          
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
        wx.hideLoading();
      },
      fail: function (res) {
        wx.hideLoading();
        console.log(res);
      }
    });
  },
  getGoodsList() {
    this.setData({
      goodsFlag:false
    })
    let urlStr = app.getNetAddresss("plugin.travel-around.frontend.goods.goods.getGoodsList");
    app._postNetWork({
      url: urlStr,
      data: this.data.query,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          let basicInfo =  res.basic_info;
          this.data.totalPage = res.data.last_page;
          if (!this.data.totalPage) {
            this.data.totalPage = 0;
          }
        this.setData({
          categoriesGoodsList: res.data.data,
          siteName:basicInfo?.home?.mailInfo?.name,
          imageUrl:basicInfo?.home?.mailInfo?.logo_url,
          goodsFlag:true
        })
        } else {
          this.data.query.page = this.data.query.page - 1;
          this.isLoadMore = false;
          this.goodsFlag = false;
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getKefu() {
    let goods_id = "";
    let urlStr = app.getNetAddresss("goods.customer-service.index");
    app._postNetWork({
      url: urlStr,
      data: {
        goods_id: goods_id,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            customer_open:res.data.customer_open == 0?false:true,
            showKefu: false,
            cservice: res.data.cservice,
            service_QRcode: res.data.service_QRcode,
            service_mobile: res.data.service_mobile,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  showService() {
    this.setData({
      showKefu: true
    })
  },
  getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.query.page >= this.data.totalPage) {
      return;
    } else {
      this.data.query.page = this.data.query.page + 1;
      let urlStr = app.getNetAddresss("plugin.travel-around.frontend.goods.goods.getGoodsList");
      app._getNetWork({
        url: urlStr,
        data: this.data.query,
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data.data;
          if (res.result == 1) {
            this.data.isLoadMore = true;
            this.setData({
              categoriesGoodsList : this.data.categoriesGoodsList.concat(list),
            })
          } else {
            this.data.query.page = this.data.query.page - 1;
            this.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();
     //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
     wx.showLoading({
      title: '刷新中...',
    })
    this.setData({
      'query.page':1,
      storeName: ""
    })
    this.getGoodsList();

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多了');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '周边游-' + this.data.siteName,
      imageUrl:this.data.imageUrl,
      path: `/packageF/tourAround/categories/categories?childrenId=${this.data.query.category}&cityCode=${this.data.query.cityCode}&city=${this.data.query.city}&longitude=${this.data.query.longitude}&latitude=${this.data.query.latitude}`
    };
  },
  onShareTimeline() {
    return {
      title: '周边游-' + this.data.siteName,
      imageUrl:this.data.imageUrl,
      path: `/packageF/tourAround/categories/categories?childrenId=${this.data.query.category}&cityCode=${this.data.query.cityCode}&city=${this.data.query.city}&longitude=${this.data.query.longitude}&latitude=${this.data.query.latitude}`
    };
  }
})